package com.yanxinim.cn.store;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.yanxinim.cn.AppConfig;
import com.yanxinim.cn.R;
import com.yanxinim.cn.store.adapter.StoreCartAdapter;
import com.yanxinim.cn.store.bean.CartInfo;
import com.yanxinim.cn.ui.base.BaseActivity;
import com.yanxinim.cn.util.JsonTool;
import com.yanxinim.cn.util.ToastUtil;
import com.yanxinim.cn.view.LoadingDialog;

import java.io.IOException;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class StoreCartActivity extends BaseActivity {
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.rv_data)
    RecyclerView rvData;
    @BindView(R.id.tv_total_money)
    TextView tvTotalMoney;
    @BindView(R.id.tv_commit)
    TextView tvCommit;
    @BindView(R.id.iv_nothing)
    ImageView ivNothing;
    @BindView(R.id.tv_clean)
    TextView tvClean;
    @BindView(R.id.ll_content)
    LinearLayout llContent;
    @BindView(R.id.ll_bottom)
    RelativeLayout llBottom;

    private StoreCartAdapter storeCartAdapter;
    private LoadingDialog loadingDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.a_store_cart_activity);
        ButterKnife.bind(this);
        loadingDialog = new LoadingDialog(this);
        ivBack.setOnClickListener(v -> finish());
        rvData.setLayoutManager(new LinearLayoutManager(this));
//        initData();
    }

    @OnClick({R.id.iv_back, R.id.tv_commit, R.id.tv_clean})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_clean:
                List<CartInfo> selectedGoods1 = storeCartAdapter.getSelectedList();
                if (selectedGoods1 != null && selectedGoods1.size() > 0) {
                    for (CartInfo cartInfo: selectedGoods1){
                        delCartData(cartInfo);
                    }
                } else {
                    ToastUtil.showToast(mContext, "请选择产品");
                }
                break;
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_commit:
                if (storeCartAdapter != null) {
                    List<CartInfo> selectedGoods = storeCartAdapter.getSelectedList();
                    if (selectedGoods != null && selectedGoods.size() > 0) {
                        Intent intent_commit_order = new Intent(StoreCartActivity.this, StoreOrderCommitActivity.class);
                        intent_commit_order.putExtra("goods", (Serializable) selectedGoods);
                        intent_commit_order.putExtra("type",1);
                        startActivity(intent_commit_order);
                    } else {
                        ToastUtil.showToast(mContext, "请选择产品");
                    }
                }
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }

    private void initData() {
        Map<String, String> params = new HashMap<>();
        params.put("pageIndex", String.valueOf(0));
        params.put("pageSize", String.valueOf(1000));
        params.put("userId", getUser().getUserId());

        HttpUtils.get().url(AppConfig.STORE_FIND_CART_DATA)
                .params(params)
                .build().execute(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                JSONObject jsonObject = JSON.parseObject(result);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tvTotalMoney.setText("共计：0.0");
                        if (jsonObject.getInteger("resultCode") == 1) {
                            JSONObject jsonObject1 = JSON.parseObject(jsonObject.getString("data"));
                            List<CartInfo> goodsList = JsonTool.jsonToList(jsonObject1.getString("pageData"), CartInfo.class);
                            if (goodsList != null && goodsList.size() > 0) {
                                storeCartAdapter = new StoreCartAdapter(StoreCartActivity.this, goodsList, getUser().getUserId());
                                storeCartAdapter.setSelectedListener(new StoreCartAdapter.SelectedListener() {
                                    @Override
                                    public void selected(List<CartInfo> goodsList1) {
                                        Double total = 0.0;
                                        for (CartInfo goods1 : goodsList1) {
                                            total = Double.parseDouble(goods1.getProductNum()) * Double.parseDouble(goods1.getProductMoney()) + total;
                                        }
                                        tvTotalMoney.setText(String.format("共计：%.2f", total));
                                    }
                                });
                                rvData.setAdapter(storeCartAdapter);
                                ivNothing.setVisibility(View.GONE);
                                rvData.setVisibility(View.VISIBLE);
                            } else {
                                ivNothing.setVisibility(View.VISIBLE);
                                rvData.setVisibility(View.GONE);
                            }

                        } else {
                            ivNothing.setVisibility(View.VISIBLE);
                            rvData.setVisibility(View.GONE);
                        }
                        Log.i("qin_store", result);
                    }
                });

            }
        });
    }

    private void delCartData(CartInfo cartInfo) {
        if (loadingDialog != null)
            loadingDialog.show();
        Map<String, String> map = new HashMap<>();
        map.put("productId", cartInfo.getProductId());
        map.put("userId", getUser().getUserId());
        HttpUtils.get().url(AppConfig.STORE_DELETE_CART)
                .params(map)
                .build()
                .execute(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        e.printStackTrace();
                        if (loadingDialog != null)
                            loadingDialog.dismiss();
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result = response.body().string();
                        JSONObject jsonObject = JSON.parseObject(result);
                        ((Activity) mContext).runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (jsonObject.getInteger("resultCode") == 1) {
                                    if (storeCartAdapter != null)
                                        storeCartAdapter.removerItem(cartInfo);
                                } else {
                                    ToastUtil.showToast(mContext, "删除失败");
                                }
                            }
                        });
                        if (loadingDialog != null)
                            loadingDialog.dismiss();
                    }
                });
    }
}
